package com.example.demosecurityjwt.security.filter;

import com.example.demosecurityjwt.security.MySecutiryConstants;
import com.example.demosecurityjwt.security.token.SmsAuthenticationToken;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

//import static com.example.demosecurityjwt.security.MySecutiryConstants.SPRING_SECURITY_FORM_CODE_KEY;
//import static com.example.demosecurityjwt.security.MySecutiryConstants.SPRING_SECURITY_FORM_MOBILE_KEY;


/**
 * @Author: bysun
 * @Date: 2019/3/29 16:37
 */
public class SmsAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {

//    private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY;
//    private String codeParameter = SPRING_SECURITY_FORM_CODE_KEY;

    private Boolean postOnly = true;

    protected SmsAuthenticationProcessingFilter() {
        super(new AntPathRequestMatcher(MySecutiryConstants.SECURITY_SMS_URL, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse httpServletResponse)
            throws AuthenticationException, IOException, ServletException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String mobile = getMobile(request);
        String code = getCode(request);
        if (mobile == null) {
            mobile = "";
        }
        if (code == null) {
            code = "";
        }
        mobile = mobile.trim();
        code = code.trim();
        AbstractAuthenticationToken authRequest = new SmsAuthenticationToken(mobile);
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    private String getMobile(HttpServletRequest request) {
        return request.getParameter(MySecutiryConstants.SPRING_SECURITY_FORM_MOBILE_KEY);
    }

    private String getCode(HttpServletRequest request) {
        return request.getParameter(MySecutiryConstants.SPRING_SECURITY_FORM_CODE_KEY);
    }

    protected void setDetails(HttpServletRequest request,
                              AbstractAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
